package com.jucai.pppeiyouclient.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.activity.ActivitiesInitiateActivity;
import com.jucai.pppeiyouclient.view.activity.MyActivitiesActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PoLocationService extends Service {
    private static final String TAG = "PoLocationService : ";
    private LocationClient mLocationClient;
    private double latitude = 0;
    private double longitude = 0;
    private String orderId;
    private List<String> listOrderId = new ArrayList<String>();
    private boolean isLocationSuccess = false;

    Timer timer;

    public PoLocationService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timer = new Timer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.e(TAG + "start Po service");

        if (mLocationClient == null) {
            mLocationClient = new LocationClient(BaseApplication.getContext());
            mLocationClient.registerLocationListener(new PoLocationListener());
            initLocation();
        }
        if(intent == null){
            return START_REDELIVER_INTENT;
        }
        Bundle bundle = intent.getExtras();
        orderId = bundle.getString("order_id");
        int type = bundle.getInt("order_id_type",-1);
        LogUtils.e(TAG + " type = " + type);

        if(type == 2){//接单
            if(listOrderId.isEmpty()){
                listOrderId.add(orderId);
            }else{
                for(int i = 0;i<listOrderId.size();i++){
                    if(listOrderId.contains(orderId)){
                        break;
                    }else{
                        listOrderId.add(orderId);
                    }
                }
            }
        }else if(type == 1){//结束订单
            if(listOrderId.contains(orderId)){
                listOrderId.remove(orderId);
            }
            LogUtils.e(TAG + " del  listOrderId = " + listOrderId.toString());
            if(listOrderId.isEmpty() || listOrderId.size() <= 0){
                stopLocation();
                stopSelf();
                return START_REDELIVER_INTENT;
            }
        }

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
               /* HashMap<String, String> param = new HashMap<>();
                param.put("orderid", orderId);
                param.put("lat", latitude + "");
                param.put("lon", longitude + "");
                param.put("member_id", LoginUtils.getMember_id(PoLocationService.this));
                param.put("token", LoginUtils.getToken(PoLocationService.this));
                param.put("time", System.currentTimeMillis() / 1000 + "");
                param.put("service", "Client_Trip.uploadTripLocation");

                LogUtils.e(TAG + "param = " + param.toString());

                CommonRequestNetData.getJsonStringDataByEncrpt(PoLocationService.this, param, new CommonRequestNetData.ResultCallBack() {
                    @Override
                    public void parseJsonString(String str) {
                        LogUtils.e(TAG + "str = " + str);

                    }

                    @Override
                    public void onError(String str) {
                        LogUtils.e(TAG + "str = " + str);
                    }
                });*/
                startLocation();
                pushDataToService();
                stopLocation();
            }
        }, 2000, 10 * 1000);

        return START_REDELIVER_INTENT;
    }

    private void pushDataToService(){
        LogUtils.e(TAG + " isLocationSuccess = " + isLocationSuccess + "   listOrderId = " + listOrderId.toString());
        if(isLocationSuccess == false){
            return;
        }
        if(listOrderId != null && !listOrderId.isEmpty()){
            for(int i = 0;i<listOrderId.size();i++){
                HashMap<String, String> param = new HashMap<>();
                param.put("orderid", listOrderId.get(i));
                param.put("lat", latitude + "");
                param.put("lon", longitude + "");
                param.put("member_id", LoginUtils.getMember_id(PoLocationService.this));
                param.put("token", LoginUtils.getToken(PoLocationService.this));
                param.put("time", System.currentTimeMillis() / 1000 + "");
                param.put("service", "Client_Trip.uploadTripLocation");

                LogUtils.e(TAG + "param = " + param.toString());

                CommonRequestNetData.getJsonStringDataByEncrpt(PoLocationService.this, param, new CommonRequestNetData.ResultCallBack() {
                    @Override
                    public void parseJsonString(String str) {
                        LogUtils.e(TAG + "str = " + str);
                    }

                    @Override
                    public void onError(String str) {
                        LogUtils.e(TAG + "str = " + str);
                    }
                });
            }
        }
    }



    @Override
    public void onDestroy() {
        LogUtils.e(TAG + "stop Po service");
        super.onDestroy();
        stopLocation();
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setLocationNotify(false);
        option.setOpenGps(true);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);
        startLocation();
    }

    private void startLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient.start();
        } else if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    private void stopLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient = null;
        }
    }

    public class PoLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation.getLocType() == BDLocation.TypeServerError
                    || bdLocation.getLocType() == BDLocation.TypeNetWorkException
                    || bdLocation.getLocType() == BDLocation.TypeCriteriaException){
                isLocationSuccess = false;
            }else{
                latitude = bdLocation.getLatitude();
                longitude = bdLocation.getLongitude();
                isLocationSuccess = true;

            }
//            LogUtils.e(TAG + "定位结束 onReceiveLocation：" + latitude + "," + longitude);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
//            LogUtils.e(TAG + "定位结束 onConnectHotSpotMessage：" + s + "," + i);
        }
    }

}
